package controller

import (
	"encoding/json"
	"example/application/blockchain"
	"example/application/lib"
	"net/http"

	"github.com/gin-gonic/gin"
)

//type Company struct {
//	Name           string    `json:"name"`            //企业名
//	Phone          string    `json:"phone"`           //联系电话
//	Account        string    `json:"account"`         //登录账号
//	Password       string    `json:"password"`        //登录密码
//	Address        string    `json:"address"`         //地址
//	CompanyType    string    `json:"company_type"`    //企业类型，供应商，采购商，金融机构
//	EnterpriseCode string    `json:"enterprise_code"` //企业统一社会信用代码
//	BankCard       string    `json:"bank_card"`       //银行卡号码
//	Balance        uint64    `json:"balance"`         //余额
//	CreateDate     time.Time `json:"create_date"`     //创建时间
//}
/*
	- 创建企业帐号
	@HttpParam: {""}
*/
func CreateCompany(context *gin.Context) {
	company := new(lib.Company)
	err := context.ShouldBind(company)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
	}

	if company.Name == "" || company.Phone == "" || company.Account == "" || company.Password == "" || company.Address == "" || company.CompanyType == "" || company.BankCard == "" || company.EnterpriseCode == "" || company.CreateDate.IsZero() {
		context.String(http.StatusBadRequest, "入参不能为空")
	}

	marshal, err := json.Marshal(company)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
	}

	resp, err := blockchain.ChannelExecute("createCompany", [][]byte{
		marshal,
	})
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
	}

	context.JSON(http.StatusOK, resp.Payload)
}

/*
	- 根据企业类型获取企业信息
	@HttpParam: company_type:string
*/
func GetCompany(context *gin.Context) {
	companyType := context.Query("company_type")
	if companyType == "" {
		context.String(http.StatusBadRequest, "入参不能为空")
	}

	resp, err := blockchain.ChannelQuery("getCompany", [][]byte{
		[]byte(companyType),
	})
	if err != nil {
		context.String(http.StatusBadRequest, err.Error())
	}

	context.JSON(http.StatusOK, resp.Payload)
}
